// router.js
import { createRouter, createWebHistory } from 'vue-router';
import store from "@/store/index.js";

const routes = [
    {
        path: '/', redirect: '/login'
    },
    {
        path: '/login',
        component: () => import('@/views/auth/LoginView.vue'),
    },
    {
        path: '/admin',
        component: () => import('@/views/AdminView.vue'),
        meta: { requiresAuth: true, userType: 'admin' }
    },
    {
        path: '/check',
        component: () => import('@/views/CheckView.vue'),
        meta: { requiresAuth: true, userType: 'check' }
    },
    {
        path: '/athlete',
        component: () => import('@/views/AthleteView.vue'),
        meta: { requiresAuth: true, userType: 'athlete' }
    },
    {
        path: '/referee',
        component: () => import('@/views/RefereeView.vue'),
        meta: { requiresAuth: true, userType: 'referee' }
    },
    {
        path: '/chiefReferee',
        component: () => import('@/views/ChiefRefereeView.vue'),
        meta: { requiresAuth: true, userType: 'chiefReferee' }
    },
    {
        path: '/presidentChiefReferee',
        component: () => import('@/views/PresidentChiefReferee.vue'),
        meta: { requiresAuth: true, userType: 'presidentChiefReferee' }
    },
    // 添加其他页面的路由
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

// 导航守卫
router.beforeEach((to, from, next) => {
    const isAuthenticated = store.state.isAuthenticated;
    const user = store.state.username;
    const userType = store.state.userType;

    if (to.meta.requiresAuth && !isAuthenticated) {
        next('/login');
    } else if (to.path === '/login' && isAuthenticated) {
        // 如果已登录且访问登录页，根据用户类型跳转到相应界面
        redirectToUserType(userType, next);
    } else {
        next();
    }
});

// 辅助函数，根据用户类型跳转到相应界面
function redirectToUserType(userType, next) {
    switch (userType) {
        case '管理员':
            next('/admin');
            break;
        case '运动员':
            next('/athlete');
            break;
        case '检录员':
            next('/check');
            break;
        case '项目裁判员':
            next('/referee');
            break;
        case '项目裁判长':
            next('/chiefReferee');
            break;
        case '总裁判长':
            next('/presidentChiefReferee');
            break;
        // 添加其他用户类型的处理
        default:
            next('/login'); // 默认跳转到登录页
    }
}

export default router;
